<template>
	<view class="inspect-item">
		<view class="item-content">
			<view class="top">
				<view v-if="connectStatus">{{$t('inspection.taskExecute.bluetoothStatus')}}：
					<text v-if="!connectedDevice" class="did">{{$t('inspection.taskExecute.notConnected')}}</text>
					<text v-else class="did">{{$t('inspection.taskExecute.connected')}} {{ connectedDevice.deviceId }}</text>
				</view>
				<view class="btn-icons" v-if="!isEdit">
					<uni-icons type="scan" size="22" color="#1e90e6" class="icon" @click="scanSensor"></uni-icons>
					<uni-icons type="list" size="25" color="#1e90e6" @click="bindSensor"></uni-icons>
				</view>
			</view>
			<view v-if="!list.length">{{$t('common.noData')}}</view>
			<scroll-view scroll-y="true" :class="isEdit ? '' : 'scroll-height'" :scroll-into-view="scrollView">
				<view class="card-cont" v-for="(item, index1) in list" :key="index1" :id="'loca-' + item.locaId">
					<view class="head">
						<view class="left">{{item.locaName}}</view>
						<view class="right">
							<view class="circle-icon" 
								v-for="(k, index2) in status.length && status" 
								:class="item.activeIndex == index2 ? item.activeIndex == '0' ? 'green' : item.activeIndex == '1' ? 'red' : item.activeIndex == '2' ? 'orange' : '' : ''"
								:key="index2"
								@click="toggleState(index1, index2)">
								<view>{{k.cdName}}</view>
							</view>
						</view>
					</view>
					<view class="body">
						<view class="body-item" v-for="(k, index) in item.data.length && item.data" :key="index">
							<template v-if="k.inspLocaStatus.includes(item.activeIndex)">
								<view class="check-title">
									<view class="check-text">
										<view class="check-done" v-if="k.checkDone">
											<image src="../../../../static/images/icon/20.png"></image>
										</view>
										<text>{{k.inspContent}}</text>
										<!-- <p>{{index+1}}.{{k.inspContent}}</p> -->
									</view>
									<view v-if="k.inspMethod===1">
										<text>{{$t('inspection.line.unit')}}：{{k.mpList.length && k.mpList[0].unit | codeFormat(unitList, 'name', 'key')}}</text>
									</view>
									<view class="check-more">
										<image v-if="!isEdit && k.inspMethod===1 && taskInfo.taskType!==1" class="space" src="../../../../static/images/icon/edit.png" @click="editMp(k)"></image>
										<image v-if="!isEdit && k.inspMethod===0 && k.execResult===1" class="space" src="../../../../static/images/icon/add.png" @click="addAbnormal(k)"></image>
										<uni-icons v-if="!isEdit" type="more-filled" size="26" color="#1E90E6" @click="viewMore(k)"></uni-icons>
									</view>
								</view>
								
								<template v-if="k.inspMethod===0">
									<view class="check-res">
										<view class="btn">
											<button :type="k.execResult===0 ? 'primary' : 'default'" @click="checkTemp(k, 0)">{{$t('inspection.taskPlan.normal')}}</button>
											<button :type="k.execResult===1 ? 'primary' : 'default'" @click="checkTemp(k, 1)">{{$t('inspection.taskPlan.abnormal')}}</button>
										</view>
									</view>
									<view v-if="k.execResult === 1">
										<abnormal-content v-if="k.showAbn" :inspection="k" :isEdit="isEdit" @remove="removeAbn" @register="registerDefect" @defect="viewDefect"></abnormal-content>
									</view>
								</template>
								
								<template v-if="k.inspMethod===1">
									<view v-for="(mp, idx) in k.mpList" :key="idx">
										<view class="check-res">
											<view class="temp-area">
												<view class="temp-desc" :class="isEdit ? 'desc-view' : ''">
													<image v-if="!isEdit && taskInfo.taskType !== 1" src="../../../../static/images/icon/cut.png" @click="removeMp(k, mp, idx)"></image>
													<text class="temp-name">{{mp.mpName}}</text>
													<input class="temp-val" 
														:class="mp.execResult === 1 ? 'red' : ''"
														type="number" 
														v-model="mp.execValue" 
														:disabled="isEdit" 
														@input="measure(k, mp)" 
														@blur="saveMeasure(k, mp)" />
												</view>
												<view class="temp-btns" :class="isEdit ? '' : mp.mpType != 'wendu' ? 'btns-long' : 'btns-short'">
													<button type="primary" size="mini" v-if="!isEdit && mp.mpMm !== 1" @click="read(k, mp)">{{$t('inspection.taskExecute.read')}}</button>
													<button type="primary" size="mini" v-if="!isEdit && mp.mpMm !== 1 && mp.mpType != 'wendu'" @click="wave(k, mp)">{{$t('inspection.taskExecute.wave')}}</button>
													<button type="primary" size="mini" @click="history(mp)">{{$t('inspection.taskExecute.history')}}</button>
												</view>
											</view>
										</view>
										<view v-if="mp.execResult === 1">
											<abnormal-content v-if="k.showAbn" :inspection="k" :isEdit="isEdit" :mp="mp" @register="registerDefect" @defect="viewDefect"></abnormal-content>
										</view>
									</view>
								</template>
								
								<view v-if="!isEdit && k.showMoreBtn" class="attachFile">
									<attach-file :attachFile="k.attachFile" :sourceData="k" :canEdit="true" @fileSet="fileSet"></attach-file>
								</view>
								
								<view v-if="isEdit && k.attachFile" class="attachFile">
									<attach-file :attachFile="k.attachFile"></attach-file>
								</view>
							</template>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		
		<view class="fixed-btn" v-if="list.length && !isEdit">
			<button type="primary" @click="saveInspect">{{$t('baseCommon.buttons.save')}}</button>
			<button type="primary" @click="nextInspect">{{btnText}}</button>
			<button type="primary" @click="issueTicket" v-if="false">{{$t('common.buttons.ticket')}}</button>
		</view>
		
		<uni-popup ref="mp" type="bottom" height="calc(100% - 92px)">
			<mp-list :insp="baseItem" :unitList="unitList" @closePop="closePop" @confirm="addMp"></mp-list>
		</uni-popup>
		
		<uni-popup ref="history" type="top" style="top: 50%;height: calc(50% - 100px);">
			<history-charts :chartData="historyData"></history-charts>
		</uni-popup>
		
		<uni-popup ref="waveHis" type="top" style="top: 50%;height: calc(50% - 115px);">
			<wave-history-charts :hisMpItem="hisMpItem" network="offline" @closePop="closePop"></wave-history-charts>
		</uni-popup>
		
		<uni-popup ref="wave" type="top" :mask-click="false" style="top: 50%;height: calc(50% - 115px);">
			<wave-charts :mpTypee="baseMp.mpType" :waveData="waveData" @readWave="readWave" @closePop="closePop" @saveWave="saveWave"></wave-charts>
		</uni-popup>
		
		<uni-popup ref="ticket" type="bottom" background-color="#fff">
			<scroll-view scroll-y="true" class="scroll-height-type">
				<uni-list>
					<uni-list-item 
						v-for="item in ticketTypes" 
						:key="item.wtTypeId" 
						:title="item.wtTypeName" 
						clickable 
						@click="toTicket(item)">
					</uni-list-item>
				</uni-list>
			</scroll-view>
		</uni-popup>
		
		<upload :taskId="taskId"></upload>
	</view>
</template>

<script>
	import upload from './components/upload.vue'
	import abnormalContent from './components/abnormalContent.vue'
	import mpList from './components/mpList.vue'
	import historyCharts from '../components/historyCharts.vue'
	import waveHistoryCharts from '../components/waveHistoryCharts.vue'
	import waveCharts from '../components/waveCharts.vue'
	import attachFile from '@/components/attach-file/attach-file-offline.vue'
	import * as sqliteUtil from '@/utils/sqlite.js'
	import * as sqliteInspect from '@/utils/business/inspectSqlite.js'
	import { notice, utilities, file } from '@/utils/common.js'
	import buleTooth from '@/utils/business/blueTooth.js'
	import { fileModifyName } from '@/api/base/file.js'
	import { getWorkTicketType, getRolePersonById } from '@/api/business/ticket.js'
	import { inspect as util } from '@/utils/business/common.js'

	export default {
		mixins: [
			buleTooth 
		],
		data() {
			return {
				list:[],
				taskInfo: {},
				status: [],
				currentIndex:0,
				currentLoca: {},
				activeStatus:'0',
				taskId:'',
				lineId: '',
				isAreaLocation: 1,
				areaId:'',
				locaId: '',
				isEdit: '',
				unitList: [],
				btnText: '',
				historyData: {},
				waveData: [],
				waveType: '',
				ticketTypes: [],
				connectedDevice: '',
				serviceId:'' ,// service UUID
				measuredArr: [],
				baseItem: {},
				baseMp: {},
				baseMpNo: '',
				hisMpItem: '',
				scrollView: '',
				beginCollectTime: '',
				endCollectTime: '',
				delayTime: 3000 ,// 传感器读取数据延时时间
				connectStatus: true
			}
		},
		components: {
			upload,
			abnormalContent,
			mpList,
			historyCharts,
			waveHistoryCharts,
			waveCharts,
			attachFile
		},
		async onLoad(params) {
			this.taskId = params.taskId
			this.areaId = params.areaId
			this.locaId = params.locaId
			this.isEdit = params.isEdit
			this.lineId = params.lineId
			this.isAreaLocation = params.isAreaLocation
			
			await this.init()
		},
		onUnload() {
			// uni.closeBluetoothAdapter({
			// 	success(res) {
			// 		console.log('关闭蓝牙模块:' + res); 
			// 	}
			// })
		},
		onShow() {
			this.onBLEConnectionStateChange()
		},
		methods:{
			async init() {
				this.btnText = this.isAreaLocation == 0 ? this.$t('inspection.taskExecute.nextDevice') : this.$t('inspection.taskExecute.nextArea')
				this.status = uni.getStorageSync('runstate')
				
				// 获取计量单位数据字典
				sqliteUtil.selectTableInfo('m_cpis_cat_dic', 'type_key', 'jldw').then(res=>{
					this.unitList = res
				})
				
				await this.getList()
				// 只有设备才会页面定位
				if(this.isAreaLocation == '0') {
					this.scrollPage()
				}
				
				if(!this.isEdit) {
					// 进入页面即开始搜索设备，解决扫码连接失败
					uni.removeStorageSync("sensorList")
					this.openBle()
					this.connectedDevice = uni.getStorageSync("bindSensor")
					if(this.connectedDevice) {
						this.onBLEConnectionStateChange()
						this.getBLEDeviceServices()
					}
				}
			},
			scrollPage() {
				let that = this
				setTimeout(()=>{
					that.scrollView = "loca-" + that.locaId
				}, 500)
			},
			async getList() {
				// 任务信息
				await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', this.taskId).then(res=>{
					// 下划线转驼峰
					utilities.formatHumpLineTransfer(res)
					this.taskInfo = res[0]
					if(this.taskInfo.taskState == '3') {
						this.isEdit = 'ok'
					}
				})
				
				// 检查项测点
				let inspMpList = []
				await sqliteUtil.selectTableInfo('m_ri_task_insp_mp', 'task_id', this.taskId).then(res => {
					utilities.formatHumpLineTransfer(res)
					if(res.length > 0) {
						inspMpList = utilities.formatDataGroup(res, 'taskInspId')
					}
				})
				
				// 异常情况
				let inspAbnList = []
				await sqliteUtil.selectTableInfo('m_ri_task_inspection_abnormal', 'task_id', this.taskId).then(res => {
					utilities.formatHumpLineTransfer(res)
					if(res.length > 0) {
						inspAbnList = utilities.formatDataGroup(res, 'taskInspId')
						
						inspAbnList.forEach(abnormal => {
							if(abnormal.dfNo) {
								sqliteUtil.selectTableInfo('m_df_information', 'df_id', abnormal.dfNo).then(res=>{
									utilities.formatHumpLineTransfer(res)
									abnormal.defectId = res[0].dfId
									abnormal.defectNo = res[0].dfNo
									abnormal.defectDesp = res[0].dfDesp
									abnormal.defectLocaId = res[0].locaId
									abnormal.defectLocaNo = res[0].locaNo
									abnormal.defectLocaName = res[0].locaName
								})
							}
						})
					}
				})
				
				// 检查项信息
				let condition = [
					{ key: "task_id", value: this.taskId },
				]
				if(this.isAreaLocation == "0") {
					condition.push({
						key: "loca_id",
						value: this.locaId
					})
				} else if(this.isAreaLocation == "1") {
					condition.push({
						key: "area_id",
						value: this.areaId
					})
				}
				await sqliteUtil.selectTableInfoMore('m_ri_task_inspection', condition).then(async res=>{
					// 下划线转驼峰
					utilities.formatHumpLineTransfer(res)
					let list = res
					let newData = {}
					let arr = []
					await list.forEach(async item => {
						if(!newData[item.locaId]) {
							newData[item.locaId] = {}
							newData[item.locaId].data = []
							newData[item.locaId].activeIndex = item.execLocaStatus == null ? this.activeStatus : item.execLocaStatus
						}
						
						item.inspLocaStatus = item.inspLocaStatus == null ? '0' : item.inspLocaStatus
						item.checkDone = item.execStatus === 1 ? true : false
						item.showMoreBtn = item.attachFile ? true : false
						
						if(!item.execLocaStatus && item.inspLocaStatus.includes('0')) {
							item.execLocaStatus = 0
						}
						
						// 测点
						item.mpList = []
						if(item.inspMethod === 1) {
							let inspMpData = inspMpList.find(r => r.taskInspId == item.taskInspId)
							item.mpList = inspMpData ? inspMpData.item : []
						}
						
						// 异常情况
						let abnormalData = inspAbnList.find(r => r.taskInspId == item.taskInspId)
						item.abnormalList = abnormalData ? abnormalData.item : []
						if(item.abnormalList.length > 0) {
							item.showAbn = true
						}
						
						newData[item.locaId].locaId = item.locaId
						newData[item.locaId].locaName = item.locaName
						
						newData[item.locaId].data.push(item)
					})
					
					for(var i in newData) {
						arr.push(newData[i])
					}
					this.list = arr
					
					this.currentLoca = this.list[this.currentIndex]
				})
			},
			toggleState(index1, index2) {
				if(this.isEdit) {
					return
				}
				this.activeStatus = index2
				this.list[index1].activeIndex = index2
				this.list[index1].data.forEach(k => {
					k.execLocaStatus = index2
				})
			},
			// 新增测点
			editMp(k) {
				this.baseItem = k
				this.$refs.mp.open()
			},
			addMp(data) {
				this.baseItem.mpList = this.baseItem.mpList.concat(data)
				this.handleInspResult(this.baseItem)
				this.closePop('mp')
			},
			// 新增异常情况
			addAbnormal(k) {
				if(k.execResult === 0) {
					return
				}
				k.abnormalList.push({
					taskInspId: k.taskInspId,
					taskId: this.taskId,
					locaId: k.locaId,
					locaNo: k.locaNo,
					locaName: k.locaName,
					assetId: k.assetId,
					assetNo: k.assetNo,
					assetName: k.assetName,
					inspPart: k.inspPart,
					inspContent: k.inspContent,
					inspStandard: k.inspStandard,
					inspMethod: k.inspMethod,
					abnormalMemo: '',
					execLocaStatus: k.execLocaStatus,
					execTime: utilities.getNowDateTime(),
					isAbnormalHandled: 0,
					handlingMemo: '',
					companyId: uni.getStorageSync('companyId'),
					createTime: utilities.getNowDateTime()
				})
			},
			// 查看更多
			viewMore(k) {
				k.showMoreBtn = !k.showMoreBtn
			},
			// 选择检查项状态
			checkTemp(k, status) {
				if(this.isEdit) {
					return
				}

				if(status === 0) {
					if(k.abnormalList.length > 0) {
						let that = this
						uni.showModal({
							title: this.$t('baseCommon.message.tips'),
							content: this.$t('inspection.message.clearAbnormal'),
							success: function (res) {
								if (res.confirm) {
									k.abnormalList = []
									that.handleCheck(k, status)
								}
							}
						})
					} else {
						this.handleCheck(k, status)
					}
				} else if(status === 1) {
					if(k.execResult != status) {
						k.abnormalList.push({
							taskInspId: k.taskInspId,
							taskId: this.taskId,
							locaId: k.locaId,
							locaNo: k.locaNo,
							locaName: k.locaName,
							assetId: k.assetId,
							assetNo: k.assetNo,
							assetName: k.assetName,
							inspPart: k.inspPart,
							inspContent: k.inspContent,
							inspStandard: k.inspStandard,
							inspMethod: k.inspMethod,
							abnormalMemo: '',
							execLocaStatus: k.execLocaStatus,
							execTime: utilities.getNowDateTime(),
							isAbnormalHandled: 0,
							handlingMemo: '',
							companyId: uni.getStorageSync('companyId'),
							createTime: utilities.getNowDateTime()
						})
						k.showAbn = true
					}
					this.handleCheck(k, status)
				}
			},
			handleCheck(k, status) {
				k.execResult = status
				k.checkDone = true
				k.execTime = utilities.getNowDateTime()
				k.execStatus = 1
				k.execUserId = uni.getStorageSync('userId')
				k.execUserName = uni.getStorageSync('userName')
				k.completeTm = utilities.getNowDateTime()
				k.updateTime = utilities.getNowDateTime()
				// 保存检查项
				this.saveOneTaskInspec(k)
			},
			// 删除异常情况
			removeAbn(k, index) {
				if(k.abnormalList.length === 1) {
					notice.toast(this.$t('inspection.message.keepLeastOne'))
					return
				}
				k.abnormalList.splice(index, 1)
			},
			// 登记缺陷
			registerDefect(k, item) {
				if(item.abnormalMemo === null) {
					item.abnormalMemo = ''
				}
				let sourceData = {
					locaId: item.locaId,
					locaNo: item.locaNo,
					locaName: item.locaName,
					assetId: item.assetId,
					assetNo: item.assetNo,
					assetName: item.assetName,
					companyCode: this.taskInfo.workDeptNo,
					dfDesp: item.abnormalMemo,
					attachFile: k.attachFile
				}
				
				let url = '/pages/business/defect/offline/detail'
				let that = this
				uni.navigateTo({
					url: url + '?type=add&source=xundianjian&sourceId='+item.taskInspId+'&sourceData='+JSON.stringify(sourceData),
					events: {
						eventData(data) {
							k.showAbn = false
							item.dfNo = data.defectId
							item.isAbnormalHandled = 1
							item.handlingMemo = that.$t('defect.message.transferredDefect')
							item.defectId = data.defectId
							item.defectLocaId = data.defectLocaId
							item.defectLocaNo = data.defectLocaNo
							item.defectLocaName = data.defectLocaName
							item.defectDesp = data.defectDesp
							setTimeout(() => {
								k.showAbn = true
							}, 100)
						}
					}
				})
			},
			// 查看缺陷
			viewDefect(k) {
				let url = '/pages/business/defectfire/offline/detail'
				uni.navigateTo({
					url: url + '?type=view&dfId=' + k.defectId
				})
			},
			// 删除测点
			removeMp(insp, mp, index) {
				if(insp.mpList.length === 1) {
					notice.toast(this.$t('inspection.message.keepLeastOneMp'))
					return
				}
				sqliteUtil.deleteTableInfo('m_ri_task_insp_mp', 'id', mp.id)
				insp.mpList.splice(index, 1)
				this.handleInspResult(insp)
				
				// 删除异常
				sqliteUtil.deleteTableInfo('m_ri_task_inspection_abnormal', 'task_insp_id', mp.taskInspId, 'mp_id', mp.id)
			},
			async history(k) {
				if(k.mpType != 'zf' && k.mpType != 'sudu') {
					await sqliteInspect.getInspectionHistory(k.mpNo).then(res=>{
						utilities.formatHumpLineTransfer(res)
						// 取最近时间的7条数据
						let mpData = res.slice(0, 7)
						k.hisToryData = mpData
						
						let xData = []
						let yData = []
						mpData && mpData.forEach(val => {
							xData.push(val.dataTime)
							yData.push(val.dataValue)
						})
						
						this.historyData = {
							categories: xData,
							series: yData
						}
					})
					this.$refs.history.open()
				} else {
					this.hisMpItem = k
					this.$refs.waveHis.open()
				}
			},
			saveInspect() {
				let result = this.handleData()
				if(this.beforeSave('save', result)) {
					this.saveInspectItem('save', result.data)
				}
			},
			nextInspect() {
				let result = this.handleData()
				let param = result.data
				let allItems = result.allItems //全部检查项
				let unchecked = result.unchecked //未检查项
				
				let flag = this.checkAbnormalMemo(param)
				
				if(flag) {
					if(allItems !== 0 && unchecked !== 0) {
						let that = this
						uni.showModal({
						    title: this.$t('baseCommon.message.tips'),
						    content: this.$t('inspection.message.notInspected') + that.btnText + '？',
						    success: function (res) {
						        if (res.confirm) {
						            uni.navigateBack()
						        } else if (res.cancel) {
						            console.log('用户点击取消');
						        }
						    }
						});
					} else {
						uni.navigateBack()
					}
				}
			},
			// 保存所有巡检项
			saveInspectItem(type, data) {
				if(!data) {
					let result = this.handleData()
					data = result.data
				}
				data.forEach(item => {
					item.taskInspectionIOList.forEach(k => {
						// 检查项未检，设备实际状态不赋值
						if(k.execStatus == 0) {
							k.execLocaStatus = null
						} else {
							k.updateTime = utilities.getNowDateTime()
						}
					})
				})
				
				data.forEach(item => {
					item.taskInspectionIOList.forEach(k => {
						// 先删除检查项测点
						sqliteUtil.deleteTableInfo('m_ri_task_insp_mp', 'task_insp_id', k.taskInspId)
						
						// 先删除异常情况
						sqliteUtil.deleteTableInfo('m_ri_task_inspection_abnormal', 'task_insp_id', k.taskInspId)
						
						// 保存检查项测点
						sqliteInspect.insertMRiTaskInspMpBatch(k.mpList)
						
						// 保存异常情况
						sqliteInspect.insertMRiTaskInspectionAbnormalBatch(k.abnormalList)
						
						// 删除附加项
						delete k.checkDone
						delete k.showMoreBtn
						delete k.mpList
						delete k.abnormalList
						delete k.showAbn
						
						k.updateTime = utilities.getNowDateTime()
					})
					
					// 保存检查项
					utilities.formatHumpLineTransfer(item.taskInspectionIOList, 'line')
					sqliteUtil.modifyTableInfoBatch('m_ri_task_inspection', item.taskInspectionIOList, ['task_insp_id'])
				})
				
				if(type == 'save') {
					notice.success(this.$t('baseCommon.message.saveSuccess'))
					this.getList()
				}
			},
			beforeSave(type, data) {
				if(!data) {
					data = this.handleData()
				}
				let param = data.data
				let allItems = data.allItems // 全部检查项
				let unchecked = data.unchecked // 未检查项
				
				let flag = true
				if(type == 'save') {
					// 是否至少检查一个检查项
					if(allItems !== 0 && unchecked === allItems) {
						flag = false
						notice.toast(this.$t('inspection.message.checkLeastOne'))
					}
				}
				if(flag) {
					// 是否异常情况说明为空
					flag = this.checkAbnormalMemo(param)
				}
				return flag
			},
			handleData() {
				let param = []
				let allItems = 0 //全部检查项
				let unchecked = 0 //未检查项

				this.list.forEach(item => {
					let obj = {}
					let itemList = []
					item.data.forEach(k => {
						// 仪抄项需要判断测点
						if(k.inspMethod === 1) {
							this.handleInspResult(k)
							k.execStatus = k.checkDone ? 1 : 0
						}
						if(!k.inspLocaStatus.includes(k.execLocaStatus)) {
							k.execStatus = 2 // 免检
							// 清除检查信息
							k.execResult = ''
							k.execTime = ''
							k.abnormalList = []
						}
						
						if(item.activeIndex == k.execLocaStatus) {
							allItems++
						}
						if(k.execStatus === 0) {
							unchecked++
						}
						
						itemList.push(k)
					})
					
					obj = {
						locaId: item.locaId,
						runState: item.activeIndex,
						taskInspectionIOList: itemList
					}
					param.push(obj)
				})
				
				return {
					data: param,
					allItems: allItems,
					unchecked: unchecked
				}
			},
			checkAbnormalMemo(data) {
				let flag = true
				data.forEach(item => {
					item.taskInspectionIOList.forEach(k => {
						if(k.abnormalList.some(r => !r.abnormalMemo)) {
							flag = false
							notice.toast(this.$t('inspection.message.fillAbnormalsSituation'))
						}
					})
				})
				return flag
			},
			// 开工作票
			async issueTicket() {
				let res = await getRolePersonById(uni.getStorageSync("userId"))
				if(res.data && res.data.isManager === "1") {
					this.$refs.ticket.open()
					this.ticketTypes = []
					getWorkTicketType().then(res => {
						res.data.records.forEach(item => {
							if (item.isOn == 1 && item.isMain == 1) {
								this.ticketTypes.push({
									wtTypeName: item.wtTypeName,
									wtTypeId: item.wtTypeId,
									wtTypeNo: item.wtTypeNo
								})
							}
						})
					})
				} else {
					notice.toast(this.$t('ticket.message.noPermisBil'))
					return
				}
			},
			toTicket(item) {
				this.$refs.ticket.close()
				
				let sourceData = {
					locaId: this.currentLoca.locaId,
					locaNo: this.currentLoca.locaNo,
					locaName: this.currentLoca.locaName,
					operationDeptId: this.taskInfo.workDeptNo,
					operationDeptName: this.taskInfo.workDeptName,
					relateXdjTaskId: this.taskId
				}
				
				let projectType = uni.getStorageSync("projectType")
				let url = "/pages/business/ticket/workTicket/workTicketBase/index"
				if(projectType == 'fire') {
					url = '/pages/business/ticket/workTicket/workTicketBase/index'
				}
				uni.navigateTo({
					url: url + '?wtTypeId=' + item.wtTypeId + "&type=add&source=xdj&sourceData=" + JSON.stringify(sourceData)
				})
			},
			measure(k, mp) {
				this.checkAbnormal(k, mp)
			},
			saveMeasure(k, mp) {
				// 保存检查项
				k.execStatus = k.checkDone ? 1 : 0
				k.updateTime = utilities.getNowDateTime()
				this.saveOneTaskInspec(k)
				
				// 保存测点数据
				this.saveMpData(mp.mpNo, mp.execValue)
			},
			scanSensor() {
				let _this = this
				uni.scanCode({
					onlyFromCamera: true,
					success: (res) => {
						console.log('二维码内容：' + res.result);
						let deviceId = res.result // res.result.split('-')[1]
						let scanDevice = {
							deviceId: deviceId
						}
						_this.connect(scanDevice, 'sacn')
						// _this.stopBluetoothDevicesDiscovery()
					}
				});
			},
			bindSensor() {
				let _this = this;
				uni.navigateTo({
					url: '/pages/business/inspect/bindSensor?connectedDevice=' + JSON.stringify(_this.connectedDevice),
					events: {
						bindSensor(device) {
							_this.connectedDevice = device
							_this.getBLEDeviceServices()
						}
					}
				})
			},
			relieveBind() {
				this.connectedDevice = ""
				uni.removeStorageSync('bindSensor')
			},
			read(k, mp) {
				this.measuredArr = []
				this.beginCollectTime = utilities.getNowDateTime()
				
				if(!this.connectedDevice) {
					notice.toast(this.$t('inspection.message.unboundSensor'))
					return
				}
				
				if(mp.mpType == 'wendu') {
					let that = this
					// 只为调起测温红外线(传感器固件升级，增加测温关闭，此处会导致测温失效)
					// that.readTemp()
					uni.showModal({
						title: that.$t('baseCommon.message.tips'),
						content: that.$t('inspection.message.aimTheTarget'),
						success: function (res) {
							if (res.confirm) {
								uni.showLoading({
								    title: that.$t('inspection.message.reading')
								});
								
								that.readTemp()
								that.handleRead(k, mp)
							}
						}
					})
				} else {
					uni.showLoading({
					    title: this.$t('inspection.message.reading')
					});
					
					if(mp.mpType == 'zf') {
						this.readVibration()
					} else if(mp.mpType == 'sudu') {
						this.readSpeed()
					} else if(mp.mpType == 'jsd') {
						this.readAcceleration()
					}
					
					this.handleRead(k, mp)
				}
			},
			wave(k, mp) {
				if(!this.connectedDevice) {
					notice.toast(this.$t('inspection.message.unboundSensor'))
					return
				}
				
				this.baseItem = k
				this.baseMp = mp
				this.baseMpNo = mp.mpNo
				this.$refs.wave.open()
			},
			handleRead(k, mp) {
				// 此处采用延时获取测量值，延时时间不得低于3秒
				setTimeout(()=>{
					uni.hideLoading()
					
					mp.execValue = this.handleResult(this.measuredArr)
					if(mp.execValue) {
						this.checkAbnormal(k, mp)
						
						// 保存检查项
						k.execStatus = k.checkDone ? 1 : 0
						k.updateTime = utilities.getNowDateTime()
						this.saveOneTaskInspec(k)
						
						// 保存测点数据
						this.saveMpData(mp.mpNo, mp.execValue)
					} else {
						this.delayTime += 1000
					}
					
					// 记录日志
					let itemType
					if(mp.mpType == 'wendu') {
						itemType = 'temp'
					} else if(mp.mpType == 'zf') {
						itemType = 'amplitude'
					} else if(mp.mpType == 'sudu') {
						itemType = 'speed'
					} else if(mp.mpType == 'jsd') {
						itemType = 'acc_speed'
					}
					this.endCollectTime = utilities.getNowDateTime()
					util.logCollectStatus({
						eqCode: this.connectedDevice.deviceId,
						itemType: itemType,
						collectState: mp.execValue ? 11 : 21,
						beginCollectTime: this.beginCollectTime,
						endCollectTime: this.endCollectTime
					})
				}, this.delayTime)
			},
			readWave(type) {
				this.beginCollectTime = utilities.getNowDateTime()
				let itemType
				
				if(this.waveType && this.waveType != type) {
					this.saveWave(this.waveType)
				}
				this.waveData = []
				this.measuredArr = []
				let mpNo = this.baseMpNo
				if(type == 'zf') {
					itemType = 'wave_amplitude'
					mpNo += "-z"
					this.readVibrationWave()
				} else if(type == 'jsd') {
					itemType = 'wave_acc_speed'
					mpNo += "-j"
					this.readAccelerationWave()
				} else if(type == 'sudu') {
					itemType = 'wave_speed'
					mpNo += "-s"
					this.readSpeedWave()
				}
				
				setTimeout(()=>{
					let resultData = this.handleWaveResult(this.measuredArr)
					this.waveData = resultData.dataList
					this.waveType = resultData.dataType
					
					if(this.baseMp.mpType == type) {
						// 记录日志
						this.endCollectTime = utilities.getNowDateTime()
						util.logCollectStatus({
							eqCode: this.connectedDevice.deviceId,
							itemType: itemType,
							collectState: this.waveData.length > 0 ? 11 : 21,
							beginCollectTime: this.beginCollectTime,
							endCollectTime: this.endCollectTime
						})
					}
				}, 1500)
			},
			// 仪抄异常情况说明
			checkAbnormal(k, item) {
				let abnormalMemo = ""
				item.execResult = 0
				item.unitName = this.unitList.find(r => r.key === item.unit).name
				if(item.execValue) {
					// 有上限，无下限
					if(item.rangeTop && !item.rangeBottom) {
						if(Number(item.execValue) > Number(item.rangeTop)) {
							abnormalMemo = item.mpName + "：" + item.execValue + item.unitName + "，超过量程上限：" + item.rangeTop + item.unitName
							item.execResult = 1
						}
					}
					// 无上限，有下限
					else if(!item.rangeTop && item.rangeBottom) {
						if(Number(item.execValue) < Number(item.rangeBottom)) {
							abnormalMemo = item.mpName + "：" + item.execValue + item.unitName + "，超过量程下限：" + item.rangeBottom + item.unitName
							item.execResult = 1
						}
					}
					// 有上限，有下限
					else if(item.rangeTop && item.rangeBottom) {
						if(Number(item.execValue) > Number(item.rangeTop) || Number(item.execValue) < Number(item.rangeBottom)) {
							abnormalMemo = item.mpName + "：" + item.execValue + item.unitName + "，超过量程：" + item.rangeTop + "~" + item.rangeBottom + item.unitName
							item.execResult = 1
						}
					}
					
					if(item.execResult === 1) {
						let abnormalData = k.abnormalList.find(r => r.mpId == item.mpId)
						if(abnormalData) {
							abnormalData.abnormalMemo = abnormalMemo
						} else {
							k.abnormalList.push({
								taskInspId: item.taskInspId,
								taskId: this.taskId,
								locaId: item.locaId,
								locaNo: item.locaNo,
								locaName: item.locaName,
								assetId: item.assetId,
								assetNo: item.assetNo,
								assetName: item.assetName,
								inspPart: k.inspPart,
								inspContent: k.inspContent,
								inspStandard: k.inspStandard,
								inspMethod: k.inspMethod,
								abnormalMemo: abnormalMemo,
								execLocaStatus: k.execLocaStatus,
								execTime: utilities.getNowDateTime(),
								isAbnormalHandled: 0,
								handlingMemo: '',
								mpId: item.mpId,
								companyId: uni.getStorageSync('companyId'),
								createTime: utilities.getNowDateTime()
							})
						}
						k.showAbn = true
					} else {
						let index = k.abnormalList.findIndex(r => r.mpId == item.mpId)
						if(index !== -1) {
							k.abnormalList.splice(index, 1)
						}
					}
					
					this.handleInspResult(k)
				}
			},
			handleInspResult(k) {
				// 只要有一个测点有数据，表示检查项已检
				let dataList = k.mpList.filter(r => r.execValue)
				if(dataList.length > 0){
					k.checkDone = true
					k.execTime = utilities.getNowDateTime()
					k.execUserId = uni.getStorageSync('userId')
					k.execUserName = uni.getStorageSync('userName')
					k.completeTm = utilities.getNowDateTime()
					
					// 已测量的测点，只要有一个异常，表示检查项异常
					if(dataList.some(r => r.execResult === 1)) {
						k.execResult = 1
					} else {
						k.execResult = 0
					}
				} else {
					k.checkDone = false
					k.execTime = null
					k.execUserId = null
					k.execUserName = null
					k.completeTm = null
					k.execResult = null
				}
			},
			closePop(type) {
				this.$refs[`${type}`].close()
			},
			saveWave(type) {
				let mpNo = this.baseMpNo
				if(type == 'zf') {
					mpNo += "-z"
				} else if(type == 'jsd') {
					mpNo += "-j"
				} else if(type == 'sudu') {
					mpNo += "-s"
				}
				
				// 保存测点数据
				if(this.waveData.length > 0) {
					// 强制截取后300个数据，防止数据长度超长
					this.waveData = this.waveData.slice(this.waveData.length-300)
					this.saveMpData(mpNo, this.waveData.join())
				}
			},
			// 保存测点
			saveMpData(mpNo, data) {
				if(data) {
					sqliteInspect.insertMEqMpData({
						mpNo: mpNo,
						dataTime: utilities.getNowDateTime(),
						dataValue: data
					})
					// 删除最近15条数据之前的记录
					sqliteInspect.getInspectionHistory(mpNo).then(res=>{
						utilities.formatHumpLineTransfer(res)
						let delData = res.slice(15)
						delData.forEach(item => {
							sqliteUtil.deleteTableInfo('m_eq_mp_data', 'mp_data_id', item.mpDataId)
						})
					})
				}
			},
			saveOneTaskInspec(item) {
				// 保存检查项
				let data = [
					{
						key: "exec_result",
						value: item.execResult,
					},
					{
						key: "exec_loca_status",
						value: item.execLocaStatus,
					},
					{
						key: "exec_time",
						value: item.execTime,
					},
					{
						key: "exec_status",
						value: item.execStatus,
					},
					{
						key: "exec_user_id",
						value: item.execUserId,
					},
					{
						key: "exec_user_name",
						value: item.execUserName,
					},
					{
						key: "complete_tm",
						value: item.completeTm,
					},
					{
						key: "update_time",
						value: item.updateTime,
					}
				]
				let condition = [
					{
						key: "task_insp_id",
						value: item.taskInspId
					}
				]
				sqliteUtil.modifyTableInfo('m_ri_task_inspection', data, condition)
				
				// 保存测点
				if(item.inspMethod === 1 && item.mpList.length > 0) {
					item.mpList.forEach(item => {
						let mpData = [
							{
								key: "exec_result",
								value: item.execResult,
							},
							{
								key: "exec_value",
								value: item.execValue,
							}
						]
						let mpCond = [
							{
								key: "id",
								value: item.id
							}
						]
						sqliteUtil.modifyTableInfo('m_ri_task_insp_mp', mpData, mpCond)
					})
				}
			},
			fileSet(data, sourceData) {
				sourceData.attachFile = data
			},
			pageBack() {
				uni.navigateBack()
			}
		},
		onBackPress() {
			if(!this.isEdit) {
				if(this.beforeSave('back')) {
					this.saveInspectItem('back')
				} else {
					return true
				}
			}
			
			var pages = getCurrentPages();
			var prevPage = pages[pages.length - 2]; //上一个页面
			prevPage.$vm.nfcData = ''
		},
		onNavigationBarButtonTap(e) {
			uni.navigateTo({
				url: "/pages/business/inspect/offline/danger?lineId=" + this.lineId
			})
			return true
		}
	}
</script>

<style lang="scss" scoped>
	.scroll-height {
		/* #ifdef APP-PLUS */
		height: calc(100vh - 105px);
		/* #endif*/
		/* #ifdef H5 */
		height: calc(100vh - 155px);
		/* #endif*/
	}
	
	.item-content {
		/* #ifdef APP-PLUS */
		height: 100%;
		/* #endif */
	}
	
	.inspect-item {
		font-size: 14px;
		position: relative;
		height: 100%;
		background: #fff;
		
		uni-button {
			border-radius: 2px;
			font-size: 14px;
		}
		
		uni-button:after {
			border: none;
		}
		
		uni-button[type=primary] {
			background-color: #1e90e6;
		}
		
		uni-button[type=default] {
			background-color: #eee;
		}
	}
		
	.top {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px;
		border-bottom: 1px solid #ddd;
		background: #fff;
		
		.did {
			color: $uni-color-success;
		}
		
		.btn-icons {
			display: flex;
			align-items: center;
			
			.icon {
				margin-right: 10px;
			}
		}
	}
	
	.head {
		display: flex;
		line-height: 40px;
		justify-content: space-between;
		padding: 5px 10px;
		border-bottom: 1px solid #DDDDDD;
		background-color: #eee;
		align-items: center;
		
		.radio {
			flex: 0.1;
		}
		
		.left {
			flex: 0.5;
			color: #1e90e6;
			line-height: 24px;
			font-size: 14px;
			font-weight: 800;
		}
		
		.right {
			flex: 0.5;
			display: flex;
			
			.circle-icon {
				margin-left: 10px;
				width: 52px;
				height: 52px;
				text-align: center;
				border: 1px solid #ddd;
				border-radius: 50%;
				padding: 5px;
				box-sizing: border-box;
				
				uni-view {
					font-size: 12px;
					background-color: #DDDDDD;
					box-sizing: border-box;
					width: 100%;
					height: 100%;
					text-align: center;
					border-radius: 50%;
				}
			}
			
			.circle-icon.red {
				uni-view {
					background-color: #f85556;
					color: #fff;
				}
			}
			
			.circle-icon.green {
				uni-view {
					background-color: #3db213;
					color: #fff;
				}
			}
			
			.circle-icon.orange {
				uni-view {
					background-color: #ffa500;
					color: #fff;
				}
			}
		}
	}
	
	.body {
		.body-item {
			padding: 0 10px;
			font-size: 14px;
			border-bottom: 1rpx solid #ddd;
			
			text {
				line-height: 25px;
				color: #333;
				padding: 8px 0;
			}
			
			.check-title {
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.check-text {
					display: flex;
				}
				
				.check-done {
					padding-top: 12px;
					padding-right: 5px;
					
					uni-image {
						width: 20px;
						height: 20px;
					}
				}
				
				.check-more {
					display: flex;
					align-items: center;
					
					image {
						width: 20px;
						height: 20px;
					}
					
					.space {
						margin-right: 5px;
					}
				}
			}
			
			.check-res {
				margin-bottom: 10px;

				.btn {
					display: flex;
					
					uni-button {
						padding: 0 25px;
					}
				}
			}
			
			.temp-area {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.temp-desc {
					display: flex;
					align-items: center;
					justify-content: space-between;
					
					image {
						width: 20px;
						height: 20px;
						margin-right: 2px;
					}
					
					.temp-name {
						flex: 0.6;
						font-size: 12px;
					}
					
					.temp-val {
						flex: 0.4;
						height: 100%;
						
						/deep/ .uni-input-input {
							background-color: #f6f6f6;
							width: 90px;
							padding:  0 10px;
							height: 40px;
						}
					}
				}
				
				.desc-view {
					width: calc(100% - 60px);
				}
				
				.temp-btns {
					display: flex;
					align-items: center;
					margin-left: 5px;
					
					uni-button {
						width: 48px;
						// margin: 0 4px;
						font-size: 12px;
						padding: 0 12px;
					}
				}
				
				.btns-short {
					min-width: 110px;
				}
				
				.btns-long {
					min-width: 162px;
				}
			}
		}
	}
	
	.fixed-btn {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		padding: 10px 5px;
		background: #f2f2f2;
		z-index: 99;
		justify-content: space-between;
		
		uni-button {
			margin: 0 5px;
			flex: 1;
			padding: 5px 0;
		}
	}
	
	.attachFile {
		margin-bottom: 10px;
	}
	
	/deep/ .uni-list-item__content-title {
		text-align: center;
	}
	
	.red {
		color: $uni-color-error;
	}
	
	.scroll-height-type {
		max-height: 350px;
	}
</style>
